import datetime
import subprocess
import time

import cv2


class PyUtil:
    @staticmethod
    def print_text(text):
        """打印日志的同时打印时间"""
        # 获取当前时间
        current_time = datetime.datetime.now()
        # 打印当前的日期和时间
        print("当前时间:", current_time.strftime("%Y-%m-%d %H:%M:%S") + " " + text)

    @staticmethod
    def shell_command(command):
        """执行adb命令并返回输出"""
        try:
            result = subprocess.check_output(command, shell=True, universal_newlines=True)
            return result
        except BaseException as e:
            # PyUtil.print_text(f"Error executing command: {e}")
            return ""


class OpenCVUtil:

    @staticmethod
    def compare_histograms(image1_path, image2_path):
        image1 = cv2.imread(image1_path)
        if image1 is None:
            return 10
        image2 = cv2.imread(image2_path)
        """比较两张图片的相似度"""
        # 将图片转换为HSV空间
        image1_hsv = cv2.cvtColor(image1, cv2.COLOR_BGR2HSV)
        image2_hsv = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV)

        # 计算直方图
        hist1 = cv2.calcHist([image1_hsv], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
        hist2 = cv2.calcHist([image2_hsv], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

        # 归一化直方图
        hist1 /= hist1.sum()
        hist2 /= hist2.sum()

        # 比较直方图，使用相关性比较
        similarity = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
        PyUtil.print_text(f'图片相似度 =  {similarity}')
        return similarity


class AdbUtil:
    @staticmethod
    def check_device_connected():
        """检查设备是否连接"""
        command = "adb devices"
        output = PyUtil.shell_command(command)
        PyUtil.print_text(output)
        if "device" in output:
            PyUtil.print_text("设备已连接")
            return True
        else:
            PyUtil.print_text("没有检测到设备")
            return False

    @staticmethod
    def check_system_server_running():
        """检查system_server进程是否运行"""
        command = "adb shell ps -A"
        output = PyUtil.shell_command(command)
        if "system_server" in output:
            # PyUtil.print_text("system_server 进程已启动")
            return True
        else:
            # PyUtil.print_text("system_server 进程未启动")
            return False

    @staticmethod
    def reboot():
        PyUtil.print_text("重启系统...")
        command = "adb reboot"
        subprocess.run(command, shell=True, text=True, capture_output=True)

    @staticmethod
    def check_device_ready():
        index = 0
        while True:
            if AdbUtil.check_system_server_running():
                break
            else:
                PyUtil.print_text("no devices/emulators found")
                if index == 5:
                    index = 0
                    AdbUtil.reboot()
                time.sleep(15)
                index = index + 1
        time.sleep(5)
        PyUtil.print_text("系统启动完毕")
        return True

    @staticmethod
    def screen_cap(image_name, display_id=0):
        """截图"""
        PyUtil.print_text("开始截图...")
        command = "adb shell rm -rf /sdcard/Download/*"
        PyUtil.shell_command(command)
        command = f"adb shell screencap -d {display_id} /sdcard/Download/{image_name}"
        PyUtil.shell_command(command)
        command = f"adb pull /sdcard/Download/{image_name}"
        PyUtil.shell_command(command)
        # 输出命令执行结果
        PyUtil.print_text("截图完毕")

    @staticmethod
    def make_win_scope(time_scope=3):
        """截图"""
        PyUtil.print_text("开始抓取WinScope...")
        # WindowManager跟踪
        command = "adb shell cmd window tracing start"
        PyUtil.shell_command(command)
        # SurfaceFlinger跟踪
        command = "adb shell su root service call SurfaceFlinger 1025 i32 1"
        PyUtil.shell_command(command)
        # 事务跟踪
        command = "adb shell su root service call SurfaceFlinger 1020 i32 1"
        PyUtil.shell_command(command)
        time.sleep(time_scope)
        command = "adb shell cmd window tracing stop"
        PyUtil.shell_command(command)
        command = "adb shell su root service call SurfaceFlinger 1025 i32 0"
        PyUtil.shell_command(command)
        command = "adb shell su root service call SurfaceFlinger 1020 i32 0"
        PyUtil.shell_command(command)
        command = "adb pull /data/misc/wmtrace ."
        PyUtil.shell_command(command)
        # 输出命令执行结果
        PyUtil.print_text("抓取WinScope完毕")

    @staticmethod
    def click_by_input_event(x, y):
        PyUtil.print_text(f"click_by_input_event{x},{y}")
        command = f"adb shell input tap {x} {y}"
        PyUtil.shell_command(command)

    @staticmethod
    def click_by_send_event(event_name, x, y):
        PyUtil.print_text(f"click_by_send_event{x},{y}")
        # 按下事件（ACTION_DOWN）
        command = f"adb shell sendevent /dev/input/{event_name} 3 57 1"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 3 53 {x}"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 3 54 {y}"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 3 58 50"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 1 330 1"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 0 0 0"
        PyUtil.shell_command(command)
        # 抬起事件（ACTION_UP）
        command = f"adb shell sendevent /dev/input/{event_name} 3 57 -1"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 1 330 0"
        PyUtil.shell_command(command)
        command = f"adb shell sendevent /dev/input/{event_name} 0 0 0"
        PyUtil.shell_command(command)
